package com.qf.aop;

import com.qf.annotation.IsLogin;
import com.qf.commons.JwtUtil;
import com.qf.entity.R;
import com.qf.entity.User;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;

@Aspect
@Component
public class LoginAop {

    /**
     * 增强 - 登录认证
     * @param joinPoint
     * @return
     */
    @Around("@annotation(com.qf.annotation.IsLogin)")
    public Object isLogin(ProceedingJoinPoint joinPoint){

        //1、获得request对象
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();

        //2、客户端传递的token 设备号
        String token = request.getParameter("token");
        String devid = request.getParameter("devid");

        //3、验证token是否合法
        User user = JwtUtil.parseToken(token, devid);

        //如果user为空，说明验签失败
        if (user == null) {

            //4、获取方法上的注解
            MethodSignature signature = (MethodSignature) joinPoint.getSignature();
            Method method = signature.getMethod();
            IsLogin isLogin = method.getAnnotation(IsLogin.class);

            //5、验证是否需要强制登录
            if (isLogin.mustLogin()) {
                //说明需要强制登录
                return new R().setCode(R.Code.MUST_LOGIN).setMsg("请提前登录");
            }
        }

        //ThreadLocal
        UserLocal.setUser(user);


        //调用目标方法
        try {
            return joinPoint.proceed();
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        } finally {
            UserLocal.setUser(null);
        }

        return null;
    }

}
